﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;
using System.Data;
using System.Configuration;
using Telerik.Web.UI;

namespace AllNations
{
    public partial class WorshipHome : MakeItWeb.Framework.MakeItWebPage
    {
        public override bool IsPageAdministrator()
        {
            return IsInRole("Administrator") || IsInRole("SermonAdmin");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var menuAdmin = radMenuLeftNav.FindItemByValue("AddVideo");
                var menuManager = radMenuLeftNav.FindItemByValue("ManageVideo");
                if (menuAdmin != null)
                    menuAdmin.Visible = IsPageAdministrator();
                if (menuManager != null)
                    menuManager.Visible = IsPageAdministrator();

                if (Request.QueryString.ToString() == "LatestSermon")
                {
                    DisplaySermonDetail();
                }
                else if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
                {
                    var item = radMenuLeftNav.Items.FindItemByValue(Request.QueryString.ToString());
                    if (item != null && item.Visible)
                    {
                        ANMCPageViews.SelectedIndex = item.Index;
                        item.Selected = true;
                    }
                }
            }
        }

        protected void lnkDownloadVideoFile_Click(object sender, EventArgs e)
        {
            Guid guidSermonId = new Guid((sender as LinkButton).CommandArgument);
            StoredProcArgs args = new StoredProcArgs();
            args["pSermonId"] = guidSermonId;
            using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetSermon", args))
            {
                Literal litPrivateVideo = new Literal()
                {
                    Text = string.Format(@"<object classid=""clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"" codebase=""http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"" width=""610"" height=""435"" id=""VideoPlayer"" align=""middle""> <param name=""allowScriptAccess"" value=""*"" /> <param name=""allowFullScreen"" value=""true"" /> <param name=""movie"" value=""/FLVPlayer.swf?video=http://www.anmc.us/SermonVideo/{0}&autoplay=true"" /> <param name""quality"" value=""high"" /><param name=""bgcolor"" value=""#ffffff"" /> <embed src=""/FLVPlayer.swf?video=http://www.anmc.us/SermonVideo/{0}&autoplay=true"" quality=""high"" bgcolor=""#000000"" width=""610"" height=""435"" name=""VideoPlayer"" align=""middle"" allowScriptAccess=""*"" allowFullScreen=""true"" type=""application/x-shockwave-flash"" pluginspage=""http://www.macromedia.com/go/getflashplayer"" /> </object>",
                            ds.Tables[0].Rows[0]["download_filename_txt"])
                };

                pldYouTubeVideo.Controls.Clear();
                pldYouTubeVideo.Controls.Add(litPrivateVideo);
                lnkDownloadVideoFile.Visible = false;
            }
        }

        protected void btSaveVideo_Click(object sender, EventArgs e)
        {
            Guid guidSeriesId = Guid.Empty;

            // try to see if the series name already exists
            if (ddSermonSeries.SelectedValue == "AddNew")
            {
                StoredProcArgs args = new StoredProcArgs();
                args["pSeriesNm"] = txtSeriesNm.Text.Trim();
                using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetSermonSeriesByName", args))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                        guidSeriesId = (Guid)ds.Tables[0].Rows[0]["sermon_series_id"];
                }

                // if the series is not there, insert
                if (guidSeriesId == Guid.Empty)
                {
                    guidSeriesId = Guid.NewGuid();
                    args["pSermonSeriesId"] = guidSeriesId;
                    if (!string.IsNullOrEmpty(txtSeriesDetailTxt.Text.Trim()))
                        args["pDetailTxt"] = txtSeriesDetailTxt.Text.Trim();
                    if (fuSeriesImage.UploadedFiles.Count > 0)
                    {
                        string sPath = Server.MapPath("~/Images/SermonSeries");
                        string sFilename = string.Format(@"{0}\{1}", sPath, fuSeriesImage.UploadedFiles[0].FileName);
                        fuSeriesImage.UploadedFiles[0].SaveAs(sFilename, true);
                        args["pSeriesImageUrl"] = fuSeriesImage.UploadedFiles[0].FileName;
                    }
                    GenericCud.ExecuteCud("proc_cm_SaveSermonSeries", args);
                }
            }
            else if (!string.IsNullOrEmpty(ddSermonSeries.SelectedValue))
            {
                guidSeriesId = new Guid(ddSermonSeries.SelectedValue);
            }

            StoredProcArgs args2 = new StoredProcArgs();
            args2["pVideoTypeId"] = int.Parse(ddVideoType.SelectedValue);
            args2["pTitleTxt"] = txtTitle.Text.Trim();
            if (guidSeriesId != Guid.Empty)
                args2["pSermonSeriesId"] = guidSeriesId;
            args2["pPassageTxt"] = txtPassage.Text.Trim();
            if (RadDateTimePickerPreachedDttm.SelectedDate.HasValue)
                args2["pPreachedDttm"] = RadDateTimePickerPreachedDttm.SelectedDate.Value;
            if (!string.IsNullOrEmpty(txtYouTubeUrl.Text.Trim()))
                args2["pYouTubeUrl"] = txtYouTubeUrl.Text.Trim();
            if (!string.IsNullOrEmpty(txtPreacherTxt.Text.Trim()))
                args2["pPreacherNm"] = txtPreacherTxt.Text.Trim();
            if (!string.IsNullOrEmpty(txtReference.Text.Trim()))
                args2["pReferenceTxt"] = txtReference.Text.Trim();
            if (!string.IsNullOrEmpty(txtDownloadFilenameTxt.Text.Trim()))
                args2["pDownloadFilenameTxt"] = txtDownloadFilenameTxt.Text.Trim();
            GenericCud.ExecuteCud("proc_cm_SaveSermon", args2);

            ResetSermonForm();

            SetPageIndex(int.Parse(ddVideoType.SelectedValue));
        }

        private void SetPageIndex(int iVideoType)
        {
            radMenuLeftNav.Items[iVideoType - 1].Selected = true;
            ANMCPageViews.SelectedIndex = viewVideoList.Index;
        }

        protected string GetVideoLink(object youtubeUrl)
        {
            if (youtubeUrl.GetType() == DBNull.Value.GetType())
                return string.Empty;

            string sUrl = youtubeUrl.ToString();
            string[] sUrlParts = sUrl.Split(new char[] { '/' });
            string sYouTubeCode = sUrlParts.LastOrDefault();

            return string.Format(@"<img src=""http://img.youtube.com/vi/{0}/1.jpg"" width=""80"" border=""0""/>", sYouTubeCode);
        }

        protected void lnkSermonDetail_Click(object sender, EventArgs e)
        {
            Guid guidSermonId = new Guid(((LinkButton)sender).CommandArgument);
            DisplaySermonDetail(guidSermonId);
        }

        /// <summary>
        /// Plays the latest sermon available
        /// </summary>
        private void DisplaySermonDetail()
        {
            StoredProcArgs args = new StoredProcArgs();
            args["pVideoTypeId"] = 1;
            var ds = GenericQry.GetDataSet("proc_cm_ListSermon", args);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DisplaySermonDetail((Guid)ds.Tables[0].Rows[0]["sermon_id"]);
            }
        }

        private void DisplaySermonDetail(Guid guidSermonId)
        {
            ANMCPageViews.SelectedIndex = viewVideoList.Index;

            StoredProcArgs args = new StoredProcArgs();
            args["pSermonId"] = guidSermonId;
            using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetSermon", args))
            {
                DataRow dr = ds.Tables[0].Rows[0];
                if (!dr.IsNull("YouTube_url"))
                {
                    string sUrl = dr["Youtube_url"].ToString();
                    string[] sUrlParts = sUrl.Split(new char[] { '/' });
                    string sYouTubeCode = sUrlParts.LastOrDefault();

                    lblSermonTitle.Text = dr["title_txt"].ToString();
                    lblSermonDateTime.Text = string.Format("{0}{1}",
                        (int)dr["video_type_id"] == 1 ? "예배날짜: " : string.Empty,
                        (int)dr["video_type_id"] == 1 ? ((DateTime)dr["preached_dttm"]).ToString("M/d/yyyy hh:mm tt") : ((DateTime)dr["preached_dttm"]).ToShortDateString());
                    lblPassageTxt.Text = !dr.IsNull("passage_txt") ? dr["passage_txt"].ToString().Replace("\n", "<br/>") : string.Empty;
                    panelDownloadLink.Visible = !dr.IsNull("download_filename_txt") && !string.IsNullOrEmpty(dr["download_filename_txt"].ToString().Trim());
                    if (!dr.IsNull("download_filename_txt") && !string.IsNullOrEmpty(dr["download_filename_txt"].ToString().Trim()))
                    {
                        lnkDownloadVideoFile.Visible = true;
                        lnkDownloadVideoFile.CommandArgument = dr["sermon_id"].ToString();
                    }

                    lblReferenceTxt.Text = string.Empty;
                    if ((int)dr["video_type_id"] == 1 && !dr.IsNull("reference_txt"))
                        lblReferenceTxt.Text = string.Format("성경구절: <strong>{0}</strong>", dr["reference_txt"]);

                    Literal litYouTubeVideo = new Literal();
                    litYouTubeVideo.Text = string.Format(@"<iframe width=""610"" height=""435"" src=""http://www.youtube.com/embed/{0}?autoplay=1&rel=0"" frameborder=""0"" allowfullscreen></iframe>", sYouTubeCode);
                    pldYouTubeVideo.Controls.Add(litYouTubeVideo);

                    ANMCPageViews.SelectedIndex = viewVideoDetail.Index;
                }
            }
        }

        private void ResetSermonForm()
        {
            ddVideoType.SelectedIndex = 0;
            txtTitle.Text = string.Empty;
            ddSermonSeries.SelectedIndex = 0;
            txtSeriesNm.Text = string.Empty;
            txtSeriesDetailTxt.Text = string.Empty;
            txtPassage.Text = string.Empty;
            RadDateTimePickerPreachedDttm.SelectedDate = null;
            txtPreacherTxt.Text = "양춘호 목사";
            txtYouTubeUrl.Text = string.Empty;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (ANMCPageViews.SelectedIndex == viewVideoList.Index)
            {
                StoredProcArgs args = new StoredProcArgs();
                args["pVideoTypeId"] = radMenuLeftNav.SelectedItem.Index + 1;
                var dsSermon = GenericQry.GetDataSet("proc_cm_ListSermon", args);

                gridSermon.MasterTableView.Columns[3].Visible = radMenuLeftNav.SelectedItem.Index == 0;
                gridSermon.MasterTableView.Columns[4].Visible = radMenuLeftNav.SelectedItem.Index == 0;
                
                gridSermon.DataSource = dsSermon;
                gridSermon.DataBind();

                SeriesCoverstory.Visible = SeriesCoverflowVisible && radMenuLeftNav.SelectedItem.Value == "SundaySermon";
                if (SeriesCoverstory.Visible)
                {
                    SeriesCoverstory.DataSource = GenericQry.GetDataSet("proc_cm_ListActiveSermonSeries", new StoredProcArgs());
                    SeriesCoverstory.DataBind();
                }
            }
            else if (ANMCPageViews.SelectedIndex == viewManageVideo.Index)
            {
                var dsSermonAll = GenericQry.GetDataSet("proc_cm_ListSermon", new StoredProcArgs());
                gridSermonManager.DataSource = dsSermonAll;
                gridSermonManager.DataBind();
            }

            if (radMenuLeftNav.SelectedItem.Value == "SundaySermon")
            {
                imgTitleList.ImageUrl = "~/Images/titleSermon.png";
                imgTitleDetail.ImageUrl = "~/Images/titleSermon.png";
            }
            else if (radMenuLeftNav.SelectedItem.Value == "SundayPraise")
            {
                imgTitleList.ImageUrl = "~/Images/titleWorshipArchive.png";
                imgTitleDetail.ImageUrl = "~/Images/titleWorshipArchive.png";
            }
            else if (radMenuLeftNav.SelectedItem.Value == "SpecialEvents")
            {
                imgTitleList.ImageUrl = "~/Images/titleSpecialEvents.png";
                imgTitleDetail.ImageUrl = "~/Images/titleSpecialEvents.png";
            }
            else
            {
                imgTitleList.ImageUrl = "~/Images/titlebar_worship.png";
                imgTitleDetail.ImageUrl = "~/Images/titlebar_worship.png";
            }
        }

        protected void lnkDeleteSermon_Click(object sender, EventArgs e)
        {
            StoredProcArgs args = new StoredProcArgs();
            args["pSermonId"] = new Guid(((LinkButton)sender).CommandArgument);
            GenericCud.ExecuteCud("proc_cm_DeleteSermon", args);
        }

        protected void radMenuLeftNav_ItemClick(object sender, Telerik.Web.UI.RadMenuEventArgs e)
        {
            if (e.Item.Value == "AddVideo")
                ANMCPageViews.SelectedIndex = viewAddVideo.Index;
            else if (e.Item.Value == "ManageVideo")
                ANMCPageViews.SelectedIndex = viewManageVideo.Index;
            else
                ANMCPageViews.SelectedIndex = viewVideoList.Index;
        }

        public bool SeriesCoverflowVisible 
        { 
            get
            {
                bool bVisible = false;
                if (bool.TryParse(ConfigurationManager.AppSettings["SermonSeriesCoverflowMode"], out bVisible))
                    return bVisible;

                return false;
            }
        }

        protected void gridSermonManager_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            var guidSermonId = (Guid)item.GetDataKeyValue("sermon_id");

            var ddVideoType = item.FindControl("ddVideoType") as DropDownList;
            var txtTitle = item.FindControl("txtTitle") as TextBox;
            var txtPassage = item.FindControl("txtPassage") as TextBox;
            var RadDateTimePickerPreachedDttm = item.FindControl("RadDateTimePickerPreachedDttm") as RadDateTimePicker;
            var txtYouTubeUrl = item.FindControl("txtYouTubeUrl") as TextBox;
            var txtPreacherTxt = item.FindControl("txtPreacherTxt") as TextBox;
            var txtReference = item.FindControl("txtReference") as TextBox;
            var ddSermonSeries = item.FindControl("ddSermonSeries") as DropDownList;
            var txtSeriesNm = item.FindControl("txtSeriesNm") as TextBox;
            var txtSeriesDetailTxt = item.FindControl("txtSeriesDetailTxt") as TextBox;
            var fuSeriesImage = item.FindControl("fuSeriesImage") as RadAsyncUpload;
            var txtDownloadFilenameTxt = item.FindControl("txtDownloadFilenameTxt") as TextBox;

            Guid guidSeriesId = Guid.Empty;

            // try to see if the series name already exists
            if (ddSermonSeries.SelectedValue == "AddNew")
            {
                StoredProcArgs args = new StoredProcArgs();
                args["pSeriesNm"] = txtSeriesNm.Text.Trim();
                using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetSermonSeriesByName", args))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                        guidSeriesId = (Guid)ds.Tables[0].Rows[0]["sermon_series_id"];
                }

                // if the series is not there, insert
                if (guidSeriesId == Guid.Empty)
                {
                    guidSeriesId = Guid.NewGuid();
                    args["pSermonSeriesId"] = guidSeriesId;
                    if (!string.IsNullOrEmpty(txtSeriesDetailTxt.Text.Trim()))
                        args["pDetailTxt"] = txtSeriesDetailTxt.Text.Trim();
                    if (fuSeriesImage.UploadedFiles.Count > 0)
                    {
                        string sPath = Server.MapPath("~/Images/SermonSeries");
                        string sFilename = string.Format(@"{0}\{1}", sPath, fuSeriesImage.UploadedFiles[0].FileName);
                        fuSeriesImage.UploadedFiles[0].SaveAs(sFilename, true);
                        args["pSeriesImageUrl"] = fuSeriesImage.UploadedFiles[0].FileName;
                    }
                    GenericCud.ExecuteCud("proc_cm_SaveSermonSeries", args);
                }
            }
            else if (!string.IsNullOrEmpty(ddSermonSeries.SelectedValue))
            {
                guidSeriesId = new Guid(ddSermonSeries.SelectedValue);
            }
            
            StoredProcArgs args2 = new StoredProcArgs();
            args2["pSermonId"] = guidSermonId;
            args2["pVideoTypeId"] = int.Parse(ddVideoType.SelectedValue);
            args2["pTitleTxt"] = txtTitle.Text.Trim();
            if (guidSeriesId != Guid.Empty)
                args2["pSermonSeriesId"] = guidSeriesId;
            args2["pPassageTxt"] = txtPassage.Text.Trim();
            if (RadDateTimePickerPreachedDttm.SelectedDate.HasValue)
                args2["pPreachedDttm"] = RadDateTimePickerPreachedDttm.SelectedDate.Value;
            if (!string.IsNullOrEmpty(txtYouTubeUrl.Text.Trim()))
                args2["pYouTubeUrl"] = txtYouTubeUrl.Text.Trim();
            if (!string.IsNullOrEmpty(txtPreacherTxt.Text.Trim()))
                args2["pPreacherNm"] = txtPreacherTxt.Text.Trim();
            if (!string.IsNullOrEmpty(txtReference.Text.Trim()))
                args2["pReferenceTxt"] = txtReference.Text.Trim();
            if (!string.IsNullOrEmpty(txtDownloadFilenameTxt.Text.Trim()))
                args2["pDownloadFilenameTxt"] = txtDownloadFilenameTxt.Text.Trim();
            GenericCud.ExecuteCud("proc_cm_SaveSermon", args2);
        }
    }
}